<?php
require_once('simple_html_dom.php');
class NewsController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','get'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		$this->render('view',array(
			'model'=> $model,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate(){
		$model = new News;
		$size  = array();
		$news = Yii::app()->db->createCommand()
		->select('source_id')
		->from('tbtt_sources')
		->queryAll();
		for($i= 0;$i<sizeof($news);$i++){
			$rss = Yii::app()->db->createCommand()
			->select('rss_link')
			->from('tbtt_rss')
			->where('source_id='.$news[$i]['source_id'])
			->queryAll();
			for($j=0;$j<sizeof($rss);$j++){
				$parse = file_get_html($rss[$j]['rss_link']);
				$items = $parse->find('item');
				$size[$i][$j]= sizeof($items);
			}
		}
		$this->render('create',array(
			'model'=>$model,'size'=>$size
		));
	}
	public function actionget()
	{
		$model=new News;
		if(isset($_GET['source'])&&isset($_GET['rss'])&&isset($_GET['item'])){
		$num_source =$_GET['source'];
		$num_rss = $_GET['rss'];
		$num_item = $_GET['item'];
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		$news = Yii::app()->db->createCommand()
		->select('source_id,source_selector')
		->from('tbtt_sources')
		->queryAll();
		//for($i= 0;$i<sizeof($news);$i++){
			$rss = Yii::app()->db->createCommand()
			->select('rss_link')
			->from('tbtt_rss')
			->where('source_id='.$news[$num_source]['source_id'])
			->queryAll();
			//for($j=0;$j<sizeof($rss);$j++){
				
				$parse = file_get_html($rss[$num_rss]['rss_link']);
				$items = $parse->find('item');
				//foreach($items as $item){
					$title = $items[$num_item]->find('title');
					if($title[0]->innertext==''){
						preg_match_all("|<title>(.*)</title>|U",$items[$num_item],$out, PREG_SET_ORDER);
						$title[0]= str_get_html($out[0][1]);
					}
					$description = $items[$num_item]->find('description');
					if($description[0]->innertext==''){
						preg_match_all("|<description>(.*)</description>|U",$items[$num_item],$out, PREG_SET_ORDER);
						$description[0]= str_get_html($out[0][1]);
					}
					$pub = $items[$num_item]->find('pubDate');
					if($pub[0]->innertext==''){
						preg_match_all("|<pub>(.*)</pub>|U",$items[$num_item],$out, PREG_SET_ORDER);
						$pub[0]= str_get_html($out[0][1]);
					}
					$link = $items[$num_item]->find('link');
					if($link[0]->innertext==''){
						preg_match_all("|<link>(.*)</link>|U",$items[$num_item],$out, PREG_SET_ORDER);
						$link[0] = str_get_html($out[0][1]);
					}
					$contents = file_get_html($link[0]->innertext);
					$content = $contents->find('.text-conent');						
						
						$_POST['News']['news_updated_at']=date("Y-m-d H:i:s");
						$_POST['News']['news_created_at']=date("Y-m-d H:i:s");
						$_POST['News']['news_title']=$title[0]->innertext;
						$_POST['News']['news_description']=$description[0]->innertext;
						$_POST['News']['news_content']=$content[0]->innertext;
						$_POST['News']['source_id']=8;
						$_POST['News']['category_id']=8;
						$_POST['News']['news_number_viewer']=10;
					$model->attributes=$_POST['News'];
					$model->save();
							
						
				//}
				
				//}	
		//}
		}
		$this->render('get',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['News']))
		{
			$_POST['News']['news_updated_at']=date("Y-m-d H:i:s");
			$model->attributes=$_POST['News'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->news_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('News');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new News('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['News']))
			$model->attributes=$_GET['News'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	


	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=News::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	
	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='news-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}